<?php
/**
 * Created by PhpStorm.
 * User: mr2longly <mr2longly@gmail.com>
 * Date: 7/14/16
 * Time: 21:10
 */

namespace Home\Model;


use Common\Library\BusinessException;
use Common\Library\Constant;
use Think\Model;
use Think\Log;
require_once ('MaiBei/Common/Library/qiniuSdk/autoload.php');
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class UploadFileModel extends Model {

    public function getCustomerCertList($customerId) {

        $certType = [
            Constant::CERT_TYPE_WITH_MERCHANT,
            Constant::CERT_TYPE_WORKER,
            Constant::CERT_TYPE_CREDIT_CARD,
            Constant::CERT_TYPE_RESIDENCE_BOOKLET,
            Constant::CERT_TYPE_MARRIAGE,
            Constant::CERT_TYPE_HOUSE,
            Constant::CERT_TYPE_DRIVER,
        ];
        $map = [
            'customer_id' => $customerId,
            'type' => ['in', $certType],
        ];

        $certList = $this->where($map)->select();

        $data = [];
        if ($certList) {
            foreach ($certList as $cert) {
                $type = $cert['type'];

                // 搞到最新的认证图片信息
                if (!isset($data[$type]) || $data[$type]['id'] < $cert['id']) {
                    $data[$type] = $cert;
                }
            }
        }

        return array_values($data);
    }

    /********************************************************************
     * 功能描述：上传图片公用方法
     * 创建时间：2016-08-05
     * 入参：
     *
     * 出参：
     */
    public function uploadImage($rootPath, $savePath, $saveName,$type=1)
    {
        try{
            $upload = new \Think\Upload();
            $upload->maxSize = 100000000; // 100 mb
            $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg');
            $upload->autoSub = true; //不允许自动创建子目录
            $upload->subName = array('date', 'Ymd'); //不允许自动创建子目录
            $upload->rootPath = $rootPath;
            $upload->savePath = $savePath;// 设置附件上传目录
            $upload->saveName = ['uniqid', $saveName];
            $ret = $upload->upload();
            if($ret) {
                foreach($ret as $k =>$v) {
                    $savePath = $v['savepath'];
                    $saveName = $v['savename'];
                    $fileKey = $v['key'];
                    if($type==1) {
                        $filePath = $_SERVER['DOCUMENT_ROOT'].'/Uploads'.$savePath.$saveName;
                    }
                    if($type==2) {
                        $filePath = $rootPath.$savePath.$saveName;
                        $savePath = '/data'.$savePath;
                    }
                    $this->uploadQiniu($savePath, $saveName, $fileKey,$filePath);
                }
            }
            
            if (!$ret) {
                BusinessException::throwException(Constant::UPLOAD_FAILED);
            }
            Log::write("图片上传成功：".json_encode($ret, JSON_UNESCAPED_UNICODE), Log::DEBUG);
        }catch (BusinessException $e){
                $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        return $ret;
    }

    public function uploadQiniu($savePath, $saveName ,$fileKey, $filePath)
    {
        $accessKey = 'xL_3cnM5bRek9skwWTe5dw2W58g2AqrMBjg8y-0X';
        $secretKey = 'wvT4qZCZFEPqgqXKb2OPgSj7keSFmjNhBTUBF4tu';

        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);

        // 要上传的空间
        $bucket = 'zhaoqianhua';

        // 生成上传 Token
        $token = $auth->uploadToken($bucket);

        // 要上传文件的本地路径
        $filePath = $_FILES[$fileKey]["tmp_name"];

        // 上传到七牛后保存的文件名
        $key = substr($savePath,1).$saveName;

        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();

        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            //print_r($err);
        } else {
            //print_r($ret);
        }
    }
}
